package com.utils;

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class MailUtils {
	/**
	 * 发送邮件的方法
	 * @param to    :收件人
	 * @param code  :邮件激活码
	 * @throws MessagingException 
	 * @throws AddressException 
	 */
	public static void sendMail(String to, String code) throws AddressException, MessagingException {
		//1.创建连接对象，连接到邮件服务器   *javax.mail.Session
		Properties props = new Properties();
		//props.setProperty("host", value);
		Session session = Session.getInstance(props, new Authenticator() {
			@Override
			protected PasswordAuthentication getPasswordAuthentication() {
				// TODO Auto-generated method stub
				return new PasswordAuthentication("service@xsb.com", "123");
			}
		});
	
		//2.创建邮件对象
		Message message = new MimeMessage(session);
		//2.1 设置发件人
		message.setFrom(new InternetAddress("service@xsb.com"));
		//2.2设置收件人
		message.setRecipient(RecipientType.TO, new InternetAddress(to));
		//2.3设置主题
		message.setSubject("来自刘帅比的激活邮件");
		//2.4设置邮件的正文
		message.setContent("<h1>来自刘帅比的激活邮件,激活请点击以下连接：</h1><h3><a href='http://localhost:8080/javaMail/ActiveCount?code=" + code + "'>确认激活</a></h3>", "text/html;charset=UTF-8");
		//3.发送一封激活邮件
		Transport.send(message);
	}
}
